//227. 基本计算器 II



/**
 * 判断o1的优先级是否大于o2
 * @param {String} o2 
 * @return {Boolean}
 */
function canCaculate(o1, o2) {
    return !((o1 === '+' || o1 === '-') && (o2 === '*' || o2 === '/'))
}

function isOp(c) {
    return c === '+' || c === '-' || c === '*' || c === '/'
}

function calc(n1, n2, op) {
    switch (op) {
        case '+':
            return n1 + n2
        case '-':
            return n1 - n2
        case '*':
            return n1 * n2
        case '/':
            return Math.floor(n1 / n2)
    }
}


/**
 * @param {string} s
 * @return {number}
 */
var calculate = function (s) {
    let sNum = []
    let sOp = []
    let ans = 0
    let lastNum = ''
    for (const c of s) {
        if (c === ' ') continue
        if (!isOp(c)) {
            //    sNum.push(c)
            lastNum += c
        } else {
            sNum.push(lastNum * 1)
            lastNum = ''
            while (sOp.length !== 0) {
                let op = sOp.pop()
                if (canCaculate(op, c)) { //可以计算
                    n2 = sNum.pop()
                    n1 = sNum.pop()
                    sNum.push(calc(n1, n2, op))
                } else {
                    sOp.push(op)
                    break
                }
            }
            sOp.push(c)
        }
    }
    sNum.push(lastNum * 1)
    while (sOp.length) {
        let c = sOp.pop()
        n2 = sNum.pop()
        n1 = sNum.pop()
        sNum.push(calc(n1, n2, c))
    }
    return sNum.pop()
};


let s = "1*2-3/4+5*6-7*8+9/10"
console.log(calculate(s))